package com.douyuehan.doubao.wechatpay.utils;

import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

public class HttpClient {
    private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
    private static final SSLContext trustAllSslContext;
    private static final SSLSocketFactory trustAllSslSocketFactory;

    private static final TrustManager[] trustAllCerts = new TrustManager[] {
            new X509TrustManager() {
                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                }

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                }

                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return new java.security.cert.X509Certificate[]{};
                }
            }
    };

    static {



        try {
            trustAllSslContext = SSLContext.getInstance("SSL");
            trustAllSslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            throw new RuntimeException(e);
        }

        trustAllSslSocketFactory = trustAllSslContext.getSocketFactory();
    }

    public static String post(String url, String param) {
        if (log.isDebugEnabled()) {
            log.debug("请求 {}  body {}", url, param);
        }
        Request request = new Request.Builder().url(url).post(RequestBody.create(MediaType.parse("application/json"), param)).build();
        return HttpClient.doRequest(request);
    }

    public static String get(String url) {
        Request request = new Request.Builder().url(url).get().build();
        return HttpClient.doRequest(request);
    }

    public static String doRequest(Request req) {

        OkHttpClient client = trustAllSslClient();

        try {
            if (log.isDebugEnabled()) {
                log.debug("请求 {}  body {}", req.toString(), req.body().contentType().toString());
            }
            Response response = client.newCall(req).execute();
            if (log.isDebugEnabled()) {
                log.debug(response.toString());
            }
            if (response.code() == 200) {
                String json = response.body().string();

                if (log.isDebugEnabled()) {
                    log.debug(json);
                }

                return json;
            } else {
                log.error("请求 {} 出错, status {} response {}", req.url(), response.code(), response.body());
            }
        } catch (IOException e) {
            log.error("请求 {} 出错, error {}, {}", req.url(), e.getMessage(), e.getStackTrace());
        }
        return null;
    }

    public static OkHttpClient trustAllSslClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.sslSocketFactory(trustAllSslSocketFactory, (X509TrustManager) trustAllCerts[0]);
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return builder.build();
    }







}
